package com.wsh.shop.head.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.wsh.shop.common.pojo.ApiResponse;
import com.wsh.shop.common.pojo.ApiResponseEnum;
import com.wsh.shop.common.servlet.BaseServlet;
import com.wsh.shop.common.util.ConstatFinalUtil;
import com.wsh.shop.users.pojo.ACart;
import com.wsh.shop.users.pojo.ACartEnum;
import com.wsh.shop.users.pojo.AMessage;
import com.wsh.shop.users.pojo.AUsers;
import com.wsh.shop.users.pojo.AUsersEnum;
import com.wsh.shop.users.service.IGoodsDbService;
import com.wsh.shop.users.service.IUsersDbService;
import com.wsh.shop.users.service.impl.GoodsDbServiceImpl;
import com.wsh.shop.users.service.impl.UsersDbServiceImpl;

/**
 * 第二个Servlet 只存储和管理员息息相关的信息 登陆后的操作
 * 
 * @author wangshMac
 */
@WebServlet(urlPatterns = "/head/UsersHeadServlet")
public class UsersHeadServlet extends BaseServlet {
    /**
     * 常量
     */
    private static final String FINA_MESSAGE_LIST = "messageList";
    
    private IGoodsDbService goodsDbService;
    private IUsersDbService usersDbService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        UsersDbServiceImpl usersDbServiceImpl = new UsersDbServiceImpl();
        GoodsDbServiceImpl goodsDbServiceImpl = new GoodsDbServiceImpl();

        goodsDbServiceImpl.setUsersDbService(usersDbServiceImpl);
        usersDbServiceImpl.setGoodsDbService(goodsDbServiceImpl);

        this.goodsDbService = goodsDbServiceImpl;
        this.usersDbService = usersDbServiceImpl;

    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /* 接收参数 */
        String method = request.getParameter("method");
        if ("main".equalsIgnoreCase(method)) {
            /* 登陆后首页 */
            main(request, response);
        } else if ("usersUpdateSubmit".equalsIgnoreCase(method)) {
            /* 更新提交 */
            usersUpdateSubmit(request, response);
        } else if ("cartList".equalsIgnoreCase(method)) {
            /* 购物车列表 */
            cartList(request, response);
        } else if ("cartInsertSubmit".equalsIgnoreCase(method)) {
            /* 添加提交购物车 */
            cartInsertSubmit(request, response);
        } else if ("cartDelete".equalsIgnoreCase(method)) {
            /* 删除购物车 */
            cartDelete(request, response);
        } else if ("logout".equalsIgnoreCase(method)) {
            /* 退出 */
            logout(request, response);
        } else if ("messageList".equalsIgnoreCase(method)) {
            messageList(request, response);
        } else if ("messageInsert".equalsIgnoreCase(method)) {
            messageInsert(request, response);
        } else if ("messageInsertSubmit".equalsIgnoreCase(method)) {
            messageInsertSubmit(request, response);
        }
    }

    private void messageInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /* 准备路径 */
        this.path = "/head/UsersHeadServlet?method=messageList";
        ServletContext application = request.getServletContext();
        List<AMessage> messageList = (List<AMessage>) application.getAttribute(FINA_MESSAGE_LIST);
        if (messageList == null) {
            messageList = new ArrayList<AMessage>();
        }
        
        AUsers users = (AUsers) this.findObjfromSession(request, "users");
        String name = request.getParameter("name");
        String content = request.getParameter("content");
        AMessage message = new AMessage();

        message.setName(name);
        message.setContent(content);
        message.setUserName(users.getNickName());
        message.setCreateTime(new Date());
        
        messageList.add(0, message);
        application.setAttribute(FINA_MESSAGE_LIST, messageList);
        
        /* 页面跳转 */
        response.sendRedirect(request.getContextPath() + this.path);
    }

    private void messageInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/users/messageInsert.jsp";
        AUsers users = (AUsers) this.findObjfromSession(request, "users");

        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    private void messageList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext application = request.getServletContext();
        List<AMessage> messageList = (List<AMessage>) application.getAttribute(FINA_MESSAGE_LIST);
        if (messageList == null) {
            messageList = new ArrayList<AMessage>();
        }
        application.setAttribute(FINA_MESSAGE_LIST, messageList);
        
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/users/messageList.jsp";

        AUsers users = (AUsers) this.findObjfromSession(request, "users");

        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /* 从session中移除数据 */
        HttpSession session = request.getSession();
        session.removeAttribute("users");
        response.sendRedirect(request.getContextPath() + "/MainHeadServlet?method=main");
    }

    /**
     * 更新
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void usersUpdateSubmit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        /* 从session中获取信息 */
        AUsers users = (AUsers) this.findObjfromSession(request, "users");
        int usersId = users.getId();
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.put("id", usersId);
        ApiResponse<AUsers> apiResponseRes = this.usersDbService.findOneUsersService(condMap);
        request.setAttribute("response", apiResponseRes.toJSON());

        users = apiResponseRes.getDataOneJava();

        boolean updateFlag = false;
        /* 根据不同的判断,页面跳转 */
        String operType = request.getParameter("operType");
        if ("update".equalsIgnoreCase(operType)) {
            String email = request.getParameter("email");
            String nickName = request.getParameter("nickName");
            String trueName = request.getParameter("trueName");
            String phone = request.getParameter("phone");
            String sex = request.getParameter("sex");

            users.setEmail(email);
            users.setNickName(nickName);
            users.setTrueName(trueName);
            users.setPhone(phone);
            users.setSex(Byte.valueOf(sex));

            updateFlag = true;
        } else if ("resetPass".equalsIgnoreCase(operType)) {
            String souPass = request.getParameter("souPass");
            String password = request.getParameter("password");
            String confirmPass = request.getParameter("confirmPass");
            if (souPass == null || "".equalsIgnoreCase(souPass) || password == null || "".equalsIgnoreCase(password)) {
                apiResponse.setCode(ApiResponseEnum.INFO_ERROR_FORMAT.getStatus());
                apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                        Collections.EMPTY_MAP);
            } else {
                if (password.equalsIgnoreCase(confirmPass)) {
                    if (users.getPassword().equalsIgnoreCase(souPass)) {
                        /* 原密码正确 */
                        users.setPassword(password);
                        updateFlag = true;
                    } else {
                        apiResponse.setCode(ApiResponseEnum.INFO_SOUPASS_INCORRECT.getStatus());
                        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                                Collections.EMPTY_MAP);
                    }
                } else {
                    apiResponse.setCode(ApiResponseEnum.INFO_TWO_PASS_NOT_SAME.getStatus());
                    apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                            Collections.EMPTY_MAP);
                }
            }
        }

        /* 更新 */
        if (updateFlag) {
            apiResponse = this.usersDbService.updateOneUsersService(users);
            session.setAttribute("users", users);
        }

        this.updateFlag = "true";
        request.setAttribute("response", apiResponse.toJSON());
        request.setAttribute("apiResponse", apiResponse);
        this.main(request, response);
    }

    /**
     * 首页
     * 
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/users/main.jsp";
        /* 从session中获取信息 */
        AUsers users = (AUsers) this.findObjfromSession(request, "users");
        int usersId = users.getId();
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.put("id", usersId);
        ApiResponse<AUsers> apiResponse = this.usersDbService.findOneUsersService(condMap);
        if (this.updateFlag == null || "".equalsIgnoreCase(this.updateFlag)) {
            /* 清空信息 */
            apiResponse.clearInfo();
        } else {
            ApiResponse<Object> apiResponseReq = (ApiResponse<Object>) request.getAttribute("apiResponse");
            if (Objects.nonNull(apiResponseReq)) {
                apiResponse.setCode(apiResponseReq.getCode());
                apiResponse.setInfo(apiResponseReq.getInfo(), Collections.EMPTY_MAP);
            }
        }
        request.setAttribute("response", apiResponse.toJSON());
        /* 根据不同的判断,页面跳转 */
        String operType = request.getParameter("operType");
        if ("update".equalsIgnoreCase(operType)) {
            /* 修改页面 */
            this.path = "/WEB-INF/jsp/head/users/usersUpdate.jsp";
        } else if ("resetPass".equalsIgnoreCase(operType)) {
            /* 修改页面 */
            this.path = "/WEB-INF/jsp/head/users/usersResetPass.jsp";
        }
        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }

    /**
     * 购物车更新提交
     * 
     * @param request
     * @param response
     * @throws IOException
     */
    private void cartDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> condMap = new HashMap<String, Object>();

        /* 按照id查询 */
        String id = request.getParameter("id");
        condMap.put("id", id);
        ApiResponse<ACart> apiResponse = this.usersDbService.findOneCartService(condMap);
        request.setAttribute("response", apiResponse.toJSON());

        ACart cart = apiResponse.getDataOneJava();
        /* 清空数量 */
        cart.setNum(0);
        cart.setStatus(ACartEnum.STATUS_DISABLED.getStatus());

        ApiResponse<Object> apiResponseDb = this.usersDbService.updateOneCartService(cart);

        /* 成功,提示 */
        JSONObject resultJSON = apiResponseDb.toJSON();
        response.sendRedirect(request.getContextPath() + "/head/UsersHeadServlet?method=cartList");
    }

    /**
     * 购物车添加提交
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void cartInsertSubmit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        AUsers users = (AUsers) this.findObjfromSession(request, "users");

        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/users/cartInsert.jsp";
        try {
            /* 需要返回json */
            String goodsId = request.getParameter("goodsId");
            String num = request.getParameter("num");

            /* 创建对象 */
            ACart cart = new ACart();

            /* 赋值 */
            cart.setUsersId(users.getId());
            cart.setGoodsId(Integer.valueOf(goodsId));
            cart.setNum(Integer.valueOf(num));
            cart.setStatus(ACartEnum.STATUS_ENABLE.getStatus());
            cart.setPubTime(new Date());

            /* 保存数据库 */
            apiResponse = this.usersDbService.saveOneCartService(cart);
            request.setAttribute("response", apiResponse.toJSON());
        } catch (Exception e) {
            ConstatFinalUtil.SYS_LOGGER.error("添加购物车报错了;", e);
            apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        /* 成功,提示 */
        JSONObject resultJSON = apiResponse.toJSON();
        this.printOut(resultJSON.toJSONString(), response);

    }

    /**
     * 购物车列表
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void cartList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /* 准备路径 */
        this.path = "/WEB-INF/jsp/head/users/cartList.jsp";

        AUsers users = (AUsers) this.findObjfromSession(request, "users");

        /* 分页信息 */
        /* 搜索条件,生成公共的搜索条件 */
        Map<String, Object> condMap = this.proccedSearch(request);
        /* 查询我的,查询启用的购物车 */
        condMap.put("usersId", users.getId());
        condMap.put("status", AUsersEnum.STATUS_ENABLE.getStatus());
        condMap.put("extend", "true");
        /*
         * 查询数据库 所有的数据以JSON的形式返回
         */
        ApiResponse<ACart> apiResponse = this.usersDbService.findCondListCartService(null, condMap);
        /* 将结果存储到Request中 */
        request.setAttribute("response", apiResponse.toJSON());

        /* 页面跳转 */
        request.getRequestDispatcher(path).forward(request, response);
    }
}
